#!/usr/bin/perl -wc

package RFCMail::DNS::DNSUtils;

use strict;
use base qw(Exporter);
use Net::DNS;

our @EXPORT_OK = qw(names_to_addrs addrs_to_names dns_lookup filtered_dns_lookup);

our $RES = Net::DNS::Resolver->new;


# turn a list of names into a list of addresses
# unresolvable names contribute nothing to the results
sub names_to_addrs {
    map {
	map {
	    $_->type eq "A" ? $_->address : ();
	} $RES->send($_, "A")->answer;
    } @_;
}


# turn a list of addresses into a list of names
# unresolvable addresses contribute nothing to the results
sub addrs_to_names {
    map {
	map {
	    $_->type eq "PTR" ? $_->ptrdname : ();
	} $RES->send($_)->answer;
    } @_;
}


sub dns_lookup {
    my @answer = $RES->send(@_)->answer;
    # This isn't the world's greatest approach to the problem, since
    # I'm only looking in the answer section and ignoring useful data
    # that may appear in the additional section.  This wouldn't be an
    # issue if Net::DNS::Resolver cached results.  It works, however,
    # and it will do for now.
    my $status = $RES->errorstring;
    die "NO/$status\n"
	if $status eq "NXDOMAIN";
    die "TF/$status\n"
	if $status ne "NOERROR";
    return (@answer);
}


sub filtered_dns_lookup {
    my ($domain, $type) = @_;
    return (map { $_->type eq $type ? $_ : () } dns_lookup($domain, $type));
}


1;
